<template>
  <div>
    <el-dialog
      title="新增语音包"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addInfo"
        :rules="rules"
        ref="refAddInfo"
        label-width="100px"
      >
        <el-form-item
          size="small"
          label="租户名称"
          prop="tenantId"
          v-if="user.roleName == 'PLATFORM_ADMIN'"
        >
          <el-select
            v-model="addInfo.tenantId"
            filterable
            placeholder="请选择"
            style="width: 360px"
            class="elSelect"
            v-loadMore="loadMore"
          >
            <el-option
              v-for="(item, i) in enterpriseList"
              :key="i"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item
          size="small"
          label="组织机构"
          prop="parentId"
          v-if="user.roleName == 'TENANT_ADMIN'"
        >
          <!-- <el-select
            v-model="addInfo.orgId"
            filterable
            placeholder="请选择单位"
            style="width: 360px"
            class="elSelect"
            v-loadMore="loadMore2"
          >
            <el-option
              v-for="(item, i) in projectList"
              :key="i"
              :label="item.orgName"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select> -->

          <TreeSearchAdd
            style="width: 100%"
            @changeOrgId="changeOrgId"
            @onClear="onClear"
            ref="refTreeSearchAdd"
          >
          </TreeSearchAdd>
        </el-form-item>

        <el-form-item
          size="small"
          label="联网单位"
          prop="orgId"
          v-if="user.roleName == 'TENANT_ADMIN'"
        >
          <el-select size="small" style="width: 100%;" clearable v-loadMore="unitMore" v-model='addInfo.orgId'
            placeholder='请选择' filterable remote :remote-method="remoteMethod" @clear="handleClear">
            <el-option v-for='item in orgList' :label='item.orgName' :value='item.id' :key='item.id'>
            </el-option>
            <div class="div_box" v-loading="unitloading" :style="unitloading ? '' : 'display: none;'"> </div>
          </el-select>
        </el-form-item>

        <el-form-item size="small" label="总条数" prop="amount">
          <el-input
            clearable
            oninput="if(isNaN(value)) { value = null } "
            placeholder="请输入"
            v-model="addInfo.amount"
            maxlength="7"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1500"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqOrgList, reqVoicePackageAdd, reqTenantList } from "@/api/api";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import TreeSearchAdd from "@components/TreeSearchAdd.vue"; //新增组织机构弹窗

export default {
  props: ["targetId"],
  name: "add",
  mixins: [loadMore],
  components: { treeselect, TreeSearchAdd },
  data() {
    return {
      projectList: [], //单位数据
      tenantList: [],
      enterpriseList: [],
      dialogVisible: false,
      addInfo: {
        amount: "",
        tenantId: "",
        orgId: "",
        parentId:"",
      },
      // 表单验证规则
      rules: {
        tenantId: [
          {
            required: true,
            message: "请选择租户名称",
            trigger: ["blur", "change"],
          },
        ],
        parentId: [{ required: true, message: "请选择组织机构", trigger: "change" }],
        orgId: [{ required: true, message: "请选择联网单位", trigger: "change" }],
        amount: [{ required: true, message: "请输入总条数", trigger: "blur" }],
      },
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,

      orgList: [],
      unitIndex: 1,
      unitPages: 10,
      unitloading: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(e) {
      if (e && this.user.roleName === "TENANT_ADMIN") {
        this.$nextTick(() => {
          this.$refs.refTreeSearchAdd.getDataList();
        });
      }
    },
  },
  methods: {
    changeOrgId(instanceId) {
      // this.addInfo.orgId = instanceId.id;
      this.addInfo.parentId = instanceId.id
      this.handleClear();
    },
    onClear() {
      this.addInfo.orgId = "";
      this.addInfo.parentId =''
      this.orgName = '';
      this.unitIndex = 1;
      this.unitPages = 10;
      this.orgList = []
    },
      // 清空
      handleClear() {
      this.orgName = '';
      this.unitIndex = 1;
      this.unitPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    // 远程搜索
    async remoteMethod(query) {
      this.addInfo.orgId = query //保留输入的值
      this.orgName = query;
      this.unitIndex = 1;
      this.unitPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    async unitMore() {
      if (this.unitIndex >= Math.ceil(this.unitPages / 10)) return
      this.unitIndex++
      this.unitloading = true;
      // 获取列表数据的方法
      await this.getOrgList()
      this.unitloading = false;
    },
    // 请求单位列表
    async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList( {
        tenantId,
        userId,
        roleName,
        orgName: this.orgName,
        parentId: this.addInfo.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.getEnterpriseList();
      this.loading = false;
    },
    // 获取租户列表
    async getEnterpriseList() {
      var res = await reqTenantList(this.sysInstanceIndex, 10);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // res.data.rows.forEach((e) => {
      //   this.enterpriseList.push({ id: e.id, name: e.name });
      // });
      this.sysInstanceTotalPages = res.data.total;
      this.enterpriseList = [...this.enterpriseList, ...res.data.rows];
    },
    editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          if (this.addInfo.amount == 0)
            return this.$modal.notifyWarning("总条数不能为0");
          if (this.user.roleName == "TENANT_ADMIN") {
            this.addInfo.tenantId = this.user.tenantId;
          }
          const res = await reqVoicePackageAdd({
            amount: this.addInfo.amount,
            tenantId: this.addInfo.tenantId,
            orgId: this.addInfo.orgId,
            roleName: this.user.roleName,
          });
          if (res.code == 10025)
            return this.$modal.notifyWarning("语音余额不足,请先联系运维充值");
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

          this.$modal.notifySuccess("新增语音包成功");
          this.closeEditDialog();
          this.$parent.PageMessagePackage();
          this.$parent.MessagePackage();
          if (this.user.roleName == "TENANT_ADMIN") {
            this.$parent.MessagePackage(); //更新统计
          }
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.$refs.refAddInfo.resetFields();
      if (this.user.roleName === "TENANT_ADMIN") {
        this.$refs.refTreeSearchAdd.onclose();
      }
      this.enterpriseList = [];
      this.projectList = [];
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.addInfo.amount = "";
      this.addInfo.tenantId = "";
      this.addInfo.orgId = "";
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if (this.$refs.refAddInfo != null) {
      this.closeEditDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");
// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
  // background: red;
  // opacity: 0.5;
}
::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束
</style>
